package com.yc.cloud.common.websocket.runnable;

import cn.hutool.core.bean.BeanUtil;
import com.corundumstudio.socketio.SocketIOClient;
import com.yc.cloud.common.websocket.core.SocketClientInfoManager;
import com.yc.cloud.common.websocket.core.SocketConstants;
import com.yc.cloud.common.websocket.core.SocketServer;
import com.yc.cloud.common.websocket.dto.MessageUserConnectedDto;
import lombok.val;

public class ConnectedMessageRunnable implements Runnable {
    private final SocketIOClient client;
    private final SocketServer socketIOService;

    public ConnectedMessageRunnable(SocketServer socketIOService, SocketIOClient client) {
        this.client = client;
        this.socketIOService = socketIOService;
    }

    @Override
    public void run() {
        if (client == null) {
            return;
        }
        val playerVo = SocketClientInfoManager.getInstance().convertPlayerVo(client);
        val message = new MessageUserConnectedDto();
        BeanUtil.copyProperties(playerVo, message);
        val room = playerVo.getRoom();
        //通知房间内所有用户,有人加入房间
        socketIOService.broadcastRoomMessageToUser(client.getNamespace(), room, SocketConstants.MESSAGE_USER_CONNECTED, message);
        //同步给新用户目前所有玩家
        val playerList = socketIOService.listByRoomId(client, room);
        client.sendEvent(SocketConstants.MESSAGE_INTRODUCE, playerList);
    }
}
